<template>
	<a-modal v-bind="option" class="file-upload-dialog">
		<a-upload v-model:file-list="fileList" v-bind="uploadOption" list-type="picture" :show-upload-list="{showPreviewIcon: true, showRemoveIcon: !props.isDetails}">
			<a-empty v-if="fileList.length === 0" :image="Empty.PRESENTED_IMAGE_SIMPLE" @click.stop />
			<a-button v-show="!props.isDetails" :disabled="props.isDetails" type="primary" ghost block style="border-style: dashed">
				<plus-outlined />
				上传附件
			</a-button>
			<template #iconRender="{file}">
				<svg-icon :icon-class="getFileIcon(file)" />
			</template>
		</a-upload>
		<template #footer>
			<div class="teleport">
				<div>
					<a-select :disabled="record.disabledSelect" v-model:value="contractTemplate" class="select" size="middle" :options="contractTemplateList" :field-names="{label: 'contractTemplateName', value: 'id'}">合同模板</a-select>
					<a-button :loading="showLoading" v-color="{color: COLOR_MAP.processing}" class="footer-button" @click="previewDownload">预览并下载合同</a-button>
				</div>

				<a-button type="primary" :disabled="!fileList.length" :loading="record.btnLoading" @click="save">提交正式合同</a-button>
			</div>
		</template>
	</a-modal>
	<!-- 通行授权弹窗 -->
	<access-authorization-dialog v-model:visible="visibles.accessAuth" :device-detail="deviceDetail" :hydropower="isShowHydropower" :is-resubmit="isResubmit" @success="cancel" />
</template>

<script lang="ts" setup>
	import {Img} from 'yuxin-base/src/types'
	import {reactive, ref, toRef, watch} from 'vue'
	import {PlusOutlined} from '@ant-design/icons-vue'
	import {useStore} from '@/store'
	import {authHeader, uploadURL} from 'yuxin-base/src/utils/axios'
	import {Empty, message} from 'ant-design-vue'
	import XEUtils from 'xe-utils'
	import {getFileIcon} from 'yuxin-base/src/utils'
	import fileApi from 'yuxin-base/src/api/file-api'
	import {RenterContractDevice} from '@/interface/contract'
	import {downPreview, tenantSigning, getContractTemplateData, renterContractDeviceDetail,getCurEleAndWaterQuantity} from '@/api/contract'
	import {COLOR_MAP} from 'yuxin-base/src/constant'
	import {isLockinEnv} from 'yuxin-base/src/utils'

	const store = useStore()

	const props = defineProps<{
		visible?: boolean
		files?: any
		bizId?: string | any
		isDetails?: boolean
		isResubmit:boolean
		houseId:string
	}>()

	const loading = ref<boolean>(false)
	const fileList = ref<Img[]>([])

	const emits = defineEmits(['update:visible', 'update:files', 'success'])
	const option = reactive({
		title: '上传附件',
		width: '600px',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
		}
	})
	const showLoading = ref(false)

	const contractTemplateList = ref([])
	const contractTemplate = ref(null)

	const save = () => {
		record.btnLoading = true
		let attachmentIds = fileList.value.map((o: any) => o.id)
		tenantSigning({contractId: props.bizId, attachmentIds}).finally(() => {
			record.btnLoading = false
			deviceAccessAuth(props.bizId)
			// emits('success')
			// cancel()
		})
	}

	/**
	 * 文件上传业务参数
	 */
	let params = reactive<any>({
		indexNum: 1,
		bizId: props.bizId
	})

	const record = reactive({
		disabledSelect: false,
		disabledButton: true,
		btnLoading: false
	})

	/**
	 * 文件上传配置
	 */
	const uploadOption = reactive({
		name: 'files',
		multiple: true,
		action: uploadURL,
		isImageUrl: () => false,
		headers: authHeader(),
		data() {
			for (const key in params) {
				if (params[key] === null || params[key] === undefined) {
					delete params[key]
				}
			}
			return params
		},
		beforeUpload() {
			params.indexNum = (fileList.value || []).length + 1
		},
		onRemove(file: any) {
			fileApi.removeFile(file.id).then(() => {
				message.success('文件删除成功')
				XEUtils.remove(fileList.value || [], item => file.id === item.id)
				emits('update:files', fileList.value)
			})
		},
		onChange({file, fileList}: any) {
			const {response, status, error} = file
			const index = fileList.findIndex((o: any) => o === file)

			if (status === 'done') {
				loading.value = false
				if (response.code === '200') {
					fileList[index] = response.data
					fileList[index].name = file.name
				} else {
					fileList.splice(index, 1)
					message.error(response.msg)
				}

				emits('update:files', fileList)
			} else if (status === 'error') {
				message.error(`上传失败：${error.status}`)
			}
		}
	})

	watch(
		() => props.visible,
		() => {
			if (props.visible) {
				getFileList()
				getContractTemplate()
			}
		}
	)

	watch(
		() => fileList.value,
		newVal => {
			console.log(newVal)
			if (newVal.length) {
				record.disabledButton = false
			} else {
				record.disabledButton = true
			}
		}
	)
	// 获取附件
	const getFileList = () => {
		if (props.bizId) {
			fileApi.getFileList(props.bizId).then(({data}: {data: Img[]}) => {
				if (data.length) {
					fileList.value = data.map(o => {
						o.name = o.fileOriginName
						return o
					})
				}
			})
		}
	}
	// 获取合同模板
	const getContractTemplate = () => {
		getContractTemplateData({}).then((res: any) => {
			contractTemplateList.value = res.data
			contractTemplate.value = res.data[0].id
		})
	}

	// 预览下载文件
	const previewDownload = () => {
		const form = {
			contractId: props.bizId,
			templateId: contractTemplate.value
		}
		showLoading.value = true
		record.disabledSelect = true
		record.disabledButton = true
		downPreview(form)
			.then((res: any) => {
				const link = document.createElement('a')
				link.href = res.data
				link.target = '_black'
				link.download = '租客合同.pdf'
				link.click()
				// downloadFile(res.data)
			})
			.finally(() => {
				showLoading.value = false
				record.disabledSelect = false
				record.disabledButton = false
			})
	}
	const cancel = () => {
		emits('success')
		emits('update:visible', false)
	}
	//通行授权查设备
	const visibles = reactive({
		accessAuth: false
	})
	//通行授权是否展示水电 续签则不展示
	const isShowHydropower = ref<boolean>(false)
	// 智能设备通行授权
	const deviceDetail = ref<RenterContractDevice>({} as RenterContractDevice)
	const deviceAccessAuth = (contractId: string) => {
		if (contractId) {
			renterContractDeviceDetail(contractId).then(({data}) => {
				data.renterInfos.forEach((item: any) => {
					item.accessAuthType = []
					item.lockAuthType = []
				})
				deviceDetail.value = data
				// showAccessLock 锁  showWaterEle 水电表 来自安全设置 是否展示
				//没有设备授权且是续租直接关闭弹窗，不展示水电
				if (!deviceDetail.value.showAccessLock) {
					cancel()
					return
				}
				if (deviceDetail.value.hasLock || deviceDetail.value.hasAccess) {
					visibles.accessAuth = true
					if (isLockinEnv()) {
						//云丁没有设备授权，不是续租，查询水电是否清零
						setEleAndWaterQuantity()
					}
				} else {
					cancel()
				}
			})
		}
	}
	// 查询房间是否绑定水电表
	const setEleAndWaterQuantity = () => {
		if (!deviceDetail.value.showWaterEle && !visibles.accessAuth) {
			cancel()
			return
		}
		getCurEleAndWaterQuantity({
			roomId: props.houseId
		}).then((res: any) => {
			//绑定水电表切水电表为预付费
			if ((res.data.bindEleMater || res.data.bindClodWaterMater || res.data.bindHotWaterMater) && res.data.billGenerateMethod !== 3) {
				visibles.accessAuth = true
				isShowHydropower.value = true
			} else {
				isShowHydropower.value = false
			}
			if (!visibles.accessAuth) {
				cancel()
			}
		})
	}
</script>

<style lang="less">
	.file-upload-dialog {
		.ant-modal-body {
			height: 300px;
			overflow: auto;
			padding: 0;

			> span {
				min-height: 100%;
				display: flex;
				flex-direction: column-reverse;
				justify-content: space-between;

				.ant-upload-select {
					position: sticky;
					bottom: 0;
					z-index: 1;
					padding: 12px;
					background: #fff;

					.ant-empty {
						margin: 13% 0;
					}
				}

				.ant-upload-list {
					padding: 8px;
					padding-bottom: 0;
					display: grid;
					grid-template-columns: repeat(2, 50%);

					&:before,
					&:after {
						content: none;
					}

					.ant-upload-list-picture-container {
						margin: 4px;
					}

					.ant-upload-list-item {
						margin: 0;
						padding: 1px;
						//border: none;
						height: 50px;

						.ant-upload-list-item-thumbnail {
							padding: 4px;

							.svg-icon {
								width: 36px;
								height: 36px;
							}
						}
					}
				}
			}
		}
		.teleport {
			display: flex;
			justify-content: space-between;
			.select {
				width: 200px;
				text-align: center;
			}
			.footer-button {
				margin-left: 10px;
				font-size: 14px;
				border: none;
			}
		}
	}
</style>
